package fr.dauphine.bookstore.frontoffice;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Session;

import fr.dauphine.bookstore.hibernate.HibernateUtil;
import fr.dauphine.bookstore.modele.Book;
import fr.dauphine.bookstore.modele.Order;

/**
 * Ajout d'un livre au panier.
 */
public final class AddBookServlet extends HttpServlet {

	/**
	 * Serial version UID.
	 */
	private static final long serialVersionUID = 8738299506492709905L;

	/**
	 * Traite la methode GET.
	 * 
	 * @param request
	 *            Requete
	 * @param response
	 *            Reponse
	 * @throws ServletException
	 *             Erreur de servlet
	 * @throws IOException
	 *             Erreur d'entree/sortie
	 */
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		Long id = Long.valueOf(request.getParameter("id"));
		Order order = SessionUtil.getOrder(request.getSession());

		if (order == null) {
			order = new Order();
		}

		Book book = (Book) CollectionUtils.find(order.getBooks().keySet(), new BeanPropertyValueEqualsPredicate("id", id));

		// Le livre est deja present dans le panier
		// On incremente simplement la quantite de 1
		if (book != null) {
			Integer quantity = order.getBooks().get(book);
			order.getBooks().put(book, quantity + 1);

			// Le livre est absent du panier
			// Il faut le charger depuis la base de donnees
		} else {
			Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();
			book = (Book) hSession.get(Book.class, id);

			order.getBooks().put(book, 1);
		}

		SessionUtil.setOrder(request.getSession(), order);
		response.sendRedirect("category.jsp?id=" + book.getCategory().getId());
	}
}
